# Name: SugarcaneDistances.py - MCBS 01/29/2015
# Description: ArcGIS code to compute distances from each field to closest sugarcane.

# import system module
import arcpy
from arcpy import env
from arcpy.sa import *


# Set workspace environment:
# env.workspace = "TransRaster.gdb"
env.workspace = "C:\Users\Marcelo\Documents\Sugarcane\Offline Data\Sugarcane distances\SugarDistances.gdb"
env.overwriteOutput = True
arcpy.CheckOutExtension("Spatial")
arcpy.env.extent = "MAXOF"

# Precision of raster (in meters):
Precision = 1000

# Canasat base name: 
BaseName = "Canasat_CS_"

# Final cost distance raster base name:
FinalRasterBase = "SugRoadDist_" 

# Input raster with moving cost:
MovingCost = "RoadCost1km"

# Years:
Years = range(2004,2014)

for y in Years:
	CanasatName   = BaseName + str(y)
	DissolvedName = "CanaDissolved_" + str(y)
	arcpy.Dissolve_management(CanasatName, DissolvedName)
	arcpy.AddField_management(DissolvedName, "dummy", "LONG")
	arcpy.CalculateField_management(DissolvedName, "dummy","1","PYTHON_9.3")
	DissolvedRaster = "CanaRaster_" + str(y)
	arcpy.FeatureToRaster_conversion(DissolvedName, "dummy", DissolvedRaster, Precision)
	outCostDist = CostDistance(DissolvedRaster, MovingCost)
	SaveCostRaster = FinalRasterBase + str(y)
	outCostDist.save(SaveCostRaster)
	arcpy.Delete_management(DissolvedRaster)
	arcpy.Delete_management(DissolvedName)
